<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>kotlin之构造函数(constructor) | 海晨忆的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  
  
  <meta name="description" content="&amp;emsp;&amp;emsp;java中的构造函数是与类名相同即可，kotlin里面的构造函数是用constructor关键字表示。">
<meta property="og:type" content="article">
<meta property="og:title" content="kotlin之构造函数(constructor)">
<meta property="og:url" content="https://haichenyi.com/2019/06/12/kotlin之构造函数-constructor/index.html">
<meta property="og:site_name" content="海晨忆的博客">
<meta property="og:description" content="&amp;emsp;&amp;emsp;java中的构造函数是与类名相同即可，kotlin里面的构造函数是用constructor关键字表示。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-06-12T14:29:05.172Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="kotlin之构造函数(constructor)">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;java中的构造函数是与类名相同即可，kotlin里面的构造函数是用constructor关键字表示。">
  
    <link rel="alternate" href="/atom.xml" title="海晨忆的博客" type="application/atom+xml">
  
  
    <link rel="icon" href="/uploads/artistic_image/head.jpg">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
  <link rel="stylesheet" href="/css/highlight.css">
  <script>
  let antiquityStorage = window.sessionStorage.getItem('antiquitySessionStorage');
  if (antiquityStorage == '' || antiquityStorage == null) {
    var antiquityLoader = '<div id="loaderbox"><div class="loader"><div class="load-roll"><div class="load-top"></div><div class="load-right"></div><div class="load-bottom"></div></div></div></div>';
    document.write(antiquityLoader);
    document.body.style.overflow = 'hidden'
  }
  </script>
</head>

<body>
  <div id="fullpage" class="mobile-nav-right">
    
      <div id="wrapper" style="background-image: url(/uploads/artistic_image/bg.jpg)" title="背景图片来自网络">
    
    
      <header id="header">
  <div id="nav-toggle" class="nav-toggle"></div>
  <div class="head-box global-width">
    <nav class="nav-box nav-right">
      
        <a class="nav-item" href="/" title
        
        >首页</a>
      
        <a class="nav-item" href="/archives" title
        
        >归档</a>
      
        <a class="nav-item" href="/about" title
        
        >简历</a>
      
    </nav>
  </div>
</header>
      <div id="middlecontent" title class="global-width sidebar-left">
        <section id="main"><article id="post-kotlin之构造函数-constructor" class="article global-container article-type-post" itemscope itemprop="blogPost">
  
    <header class="article-header">
      
  
    <h1 class="article-title" itemprop="name">
      kotlin之构造函数(constructor)
    </h1>
  

    </header>
  
  <div class="article-meta">
    <a href="/2019/06/12/kotlin之构造函数-constructor/" class="article-date">
  <time datetime="2019-06-12T14:27:43.000Z" itemprop="datePublished">2019-06-12</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/kotlin/">kotlin</a>
  </div>

    
  </div>
  
    <span id="busuanzi_container_page_pv">
      本文总阅读量<span id="busuanzi_value_page_pv"></span>次
    </span>
  

  <div class="article-inner">
    
    <div class="article-content article-content-cloud doorframe mac" itemprop="articleBody">
      
        <p>&emsp;&emsp;java中的构造函数是与类名相同即可，kotlin里面的构造函数是用constructor关键字表示。</p>
<a id="more"></a>
<p>&emsp;&emsp;kotlin里面的构造函数分为主构造函数和次构造函数。<strong>主构造函数只能有一个，次构造函数个数不限制，可以有一个或者多个</strong></p>
<h3 id="constructor-NaN"><a href="#constructor-NaN" class="headerlink" title="constructor"></a>constructor</h3><p>&emsp;&emsp;啥是主构造方法？啥是次构造方法呢？</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">//主构造方法如下，跟在类名后面</span><br><span class="line">class Person constructor(name:String)&#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class Person constructor()&#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line">//当主构造方法没有任何注解或者可见性修饰符时，可以省略，写成下面这样</span><br><span class="line">class Person &#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//这种就是有注解标记的主构造方法，不能省略</span><br><span class="line">class Person @Inject internal constructor()&#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//次构造方法，一个无参的次构造方法，一个有一个参数的次构造方法</span><br><span class="line"></span><br><span class="line">class Person &#123;</span><br><span class="line">    constructor()&#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    constructor(name:String)&#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;我们可以看到主构造方法是没有方法体的，那么，我们需要初始化的数据应该放到哪呢？kotlin提供了init方法，给我们初始化数据。</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">class Person constructor()&#123;</span><br><span class="line">    init&#123;</span><br><span class="line">        print(&quot;111&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    init&#123;</span><br><span class="line">        println()</span><br><span class="line">        print(&quot;222&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var p = Person()</span><br><span class="line">//这里我们会看到打印台打印:111，换行打印222</span><br><span class="line">//这里构造方法是按顺序执行的</span><br><span class="line">//我都是自己写代码跑的结果，不想贴图了，自己写了跑一边，印象会更加深刻</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;那么，问题来了，次构造方法有方法体，会执行这个init模块吗？</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">class Person&#123;</span><br><span class="line">    constructor()&#123;</span><br><span class="line">        println()</span><br><span class="line">        print(&quot;111&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    init&#123;</span><br><span class="line">        print(&quot;222&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//这里我们会看到打印台打印:222，换行打印111</span><br></pre></td></tr></table></figure></div>
<p>结论：<strong><em>不管是什么构造方法，先执行init模块逻辑，后执行构造方法的逻辑</em></strong></p>
<h3 id="this，super"><a href="#this，super" class="headerlink" title="this，super"></a>this，super</h3><p>&emsp;&emsp;简单的说一下继承,this和super两个关键字，跟java差不多；</p>
<p>&emsp;&emsp;this是调用自己的，super是调用父类的</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">open class AAA &#123;</span><br><span class="line">        constructor(name: String) &#123;</span><br><span class="line">            Log.v(&quot;wz&quot;, &quot;$name A&quot;)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        constructor(name: String, age: Int) &#123;</span><br><span class="line">            Log.v(&quot;wz&quot;, &quot;我是AAA的两个参数的构造方法&quot;)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        init &#123;</span><br><span class="line">            Log.v(&quot;wz&quot;, &quot;222&quot;)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    class BBB : AAA &#123;</span><br><span class="line">        constructor(name: String) : this(name, 0) &#123;</span><br><span class="line">            Log.v(&quot;wz&quot;, &quot;我是BBB的一个参数的构造方法&quot;)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        constructor(name: String, age: Int) : super(name, age) &#123;</span><br><span class="line">            Log.v(&quot;wz&quot;, &quot;我是BBB的两个参数的构造方法&quot;)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    var b = BBB(&quot;小王&quot;)</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;类BBB继承类AAA，其中BBB分别有一个参数的构造方法和两个参数的构造方法；一个参数的构造方法用的this关键字调用自己的两个参数的构造；而两个参数的构造方法用的super关键字调用的父类两个参数的构造方法；这里控制台打印的数据：</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">222</span><br><span class="line">我是AAA的两个参数的构造方法</span><br><span class="line">我是BBB的两个参数的构造方法</span><br><span class="line">我是BBB的一个参数的构造方法</span><br></pre></td></tr></table></figure></div>
<h3 id="重写set-get方法"><a href="#重写set-get方法" class="headerlink" title="重写set/get方法"></a>重写set/get方法</h3><p>说到了这个类，讲一下怎么重写属性的set/get方法</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">open class Person &#123;</span><br><span class="line">        var name: String = &quot;&quot;</span><br><span class="line">            set(value) &#123;</span><br><span class="line">                field = value + &quot;www&quot;</span><br><span class="line">            &#125;</span><br><span class="line">            get() &#123;</span><br><span class="line">                return field + &quot;zzz&quot;</span><br><span class="line">            &#125;</span><br><span class="line">        var age: Int = 0</span><br><span class="line">            set(value) &#123;</span><br><span class="line">                field = if (value &gt;= 20) 20 else value</span><br><span class="line">            &#125;</span><br><span class="line">            get() &#123;</span><br><span class="line">                return field * 2</span><br><span class="line">            &#125;</span><br><span class="line">        var address: String = &quot;&quot;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;这里一个person类，里面有三个属性：name，age，address；在name和age下面分别写了set，get方法，address没写。</p>
<p><strong>重点：</strong></p>
<ol>
<li>你想重写哪个属性的set，get方法，就在哪个属性下方写set，get方法，不用成对出现，可以只重写set方法，也可以只重写get方法</li>
<li>用field表示你想要的值</li>
</ol>
<p>&emsp;&emsp;这里，我就只重写了name和age的set，get方法，没有重写address的set，get方法</p>
<p>&emsp;&emsp;这里，我再存名字的时候在名字的后面加上了www，在获取的时候又加上了zzz，也就是说，如果你这里name传的是”小王”，那么你用get方法取到的name的值应该是”小王wwwzzz”</p>
<p>&emsp;&emsp;存age的时候，自己分析一下吧，很简单。</p>

      
    </div>
    
      <footer class="article-footer">
        完
      </footer>
    
  </div>
  
    
<nav id="article-nav">
  <div class="article-nav-block">
    
      <a href="/2019/06/14/kotlin之扩展方法/" id="article-nav-newer" class="article-nav-link-wrap">
        <strong class="article-nav-caption"></strong>
        <div class="article-nav-title">
          
            kotlin之扩展方法
          
        </div>
      </a>
    
  </div>
  <div class="article-nav-block">
    
      <a href="/2019/06/11/kotlin之扩展函数let，run，also，apply/" id="article-nav-older" class="article-nav-link-wrap">
        <div class="article-nav-title">kotlin之扩展函数let，run，also，apply</div>
        <strong class="article-nav-caption"></strong>
      </a>
    
  </div>
</nav>

    
  
  
</article>
</section>
        <aside id="sidebar">
  
    <div class="widget-box">
  <div class="avatar-box avatar-item">
    <img class="avatar" src="/uploads/artistic_image/head.jpg" title="头像来自网络"></img>
    <h3 class="avatar-name">
      
        海晨忆
      
    </h3>
    <p class="avatar-slogan">
      先谋生，再谋爱。人间值得，未来可期。
    </p>
  </div>
</div>


  
    
  <div class="widget-box">
    <h3 class="widget-title">分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android-Socket/">Android -Socket</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-加密算法/">Android -加密算法</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-常用功能/">Android -常用功能</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-框架/">Android -框架</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-源码解析/">Android -源码解析</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-自定义view/">Android -自定义view</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-设计模式/">Android -设计模式</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/JAVA-并发/">JAVA -并发</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java-SpringBoot/">Java -SpringBoot</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Tomcat/">Tomcat</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/kotlin/">kotlin</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-JDBC/">数据库 -JDBC</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-MySQL/">数据库 -MySQL</a></li></ul>
    </div>
  </div>


  
    

  
    
  
    
  <div class="widget-box">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">July 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/11/">November 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/10/">October 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/09/">September 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/08/">August 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">July 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">June 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">October 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/">May 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">March 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/">February 2018</a></li></ul>
    </div>
  </div>

  
    
  <div class="widget-box">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/07/27/JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁/">JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁</a>
          </li>
        
          <li>
            <a href="/2021/07/19/JAVA—线程同步器AQS/">JAVA—线程同步器AQS</a>
          </li>
        
          <li>
            <a href="/2021/07/07/Android模拟点击/">Android模拟点击</a>
          </li>
        
          <li>
            <a href="/2019/11/27/SpringBoot系列-消息-RabbitMQ-（二十）/">SpringBoot系列-消息(RabbitMQ)（二十）</a>
          </li>
        
          <li>
            <a href="/2019/11/13/SpringBoot系列-Docker（十九）/">SpringBoot系列-Docker（十九）</a>
          </li>
        
      </ul>
    </div>
  </div>

  
      <div class="widget-box">
    <h3 class="widget-title">友情链接</h3>
    <div class="widget">
      
        <a class="hrf" style="display: block;" href="https://github.com/haichenyi" title target='_blank'
        >Github</a>
      
        <a class="hrf" style="display: block;" href="https://www.jianshu.com/u/6077ee440c37" title target='_blank'
        >简书</a>
      
        <a class="hrf" style="display: block;" href="https://blog.csdn.net/qq_27634797" title target='_blank'
        >CSDN</a>
      
    </div>
  </div>

  
</aside>
      </div>
      <footer id="footer">
  <div class="foot-box footers global-width">
    &copy;2017-2021 海晨忆 &nbsp;&nbsp;
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">阁下是第<span id="busuanzi_value_site_pv"></span>个访客</span>
  </div>
</footer>
      <script src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
if (!window.jQuery) {
var script = document.createElement('script');
script.src = "/js/jquery-2.0.3.min.js";
document.body.write(script);
}
</script>

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



    </div>
    <nav id="mobile-nav" class="mobile-nav-box">
  <div class="mobile-nav-img mobile-nav-top"></div>
  
    <a href="/" class="mobile-nav-link">首页</a>
  
    <a href="/archives" class="mobile-nav-link">归档</a>
  
    <a href="/about" class="mobile-nav-link">简历</a>
  
  <div class="mobile-nav-img  mobile-nav-bottom"></div>
</nav>    
  </div>
</body>
</html>